<template>
  <view class="invite-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" size="20" color="#333"></u-icon>
        </view>
        <view class="navbar-title">{{ useT('邀请好友') }}</view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 邀请详情区域 -->
      <view class="invite-details">
        <view class="commission-text">
          {{ useT('推荐好友最多赚取') }}
          <text class="highlight">50%</text>
          {{ useT('佣金') }}
        </view>
        <view class="sub-text">{{ useT('邀请的朋友越多,返佣越高') }}</view>
        <view class="rules-link" @click="showRules">{{ useT('邀请规则') }}</view>
      </view>

      <!-- 插图区域 -->
      <view class="illustration-section">
        <image src="@/static/mine/inviteBg.png" class="invite-bg-image" mode="aspectFit"></image>
      </view>

      <!-- 邀请码和链接区域 -->
      <view class="invite-info-card">
        <!-- 邀请码 -->
        <view class="info-item">
          <view class="info-label">{{ useT('邀请码') }}</view>
          <view class="info-content">
            <text class="info-value">{{ inviteCode }}</text>
            <view class="copy-btn" @click="copyInviteCode">
              <u-icon name="/static/mine/copy.png" size="16" color="#12C284"></u-icon>
            </view>
          </view>
        </view>

        <!-- 邀请链接 -->
        <view class="info-item">
          <view class="info-label">{{ useT('下载链接') }}</view>
          <view class="info-content">
            <text class="info-value">{{ inviteLink }}</text>
            <view class="copy-btn" @click="copyInviteLink">
              <u-icon name="/static/mine/copy.png" size="16" color="#12C284"></u-icon>
            </view>
          </view>
        </view>
      </view>

      <!-- 查看邀请海报按钮 -->
      <view class="action-button" @click="viewPoster">{{ useT('查看邀请海报') }}</view>
      <view class="qrcode-container">
        <up-qrcode ref="qrcode" cid="ex001" :size="200" :val="inviteLink" showLoading loadingText="loading..." @result="onQrcodeResult"></up-qrcode>
      </view>
    </view>

    <!-- 海报弹窗 -->
    <u-popup v-model:show="showPoster" mode="bottom" :round="10" bg-color="transparent" :closeable="false" @close="closePoster">
      <view class="poster-container">
        <view class="poster-image">
          <image class="poster-image-item" :src="posterImage.path" mode="widthFix" />
        </view>
        <view class="poster-actions">
          <view class="download-btn" @click="downloadPoster">{{ useT('下载海报') }}</view>
          <view class="cancel-btn" @click="closePoster">{{ useT('取消') }}</view>
        </view>
      </view>
    </u-popup>
    <up-poster ref="poster" :json="posterConfig" @export="onPosterSuccess"></up-poster>
  </view>
</template>

<script setup>
import { getSpreadBanner } from '@/api/invite.js';
import { useUserStore } from '@/stores';
import { useT } from '@/utils/i18n.js';
import { onMounted, reactive, ref } from 'vue';
const userStore = useUserStore();

// 响应式数据
const inviteCode = ref('');
const inviteLink = ref('');
const showPoster = ref(false);
const poster = ref(null);
const posterImage = ref('');
// 海报配置
const posterConfig = reactive({
  css: {
    width: '600rpx',
    height: '920rpx',
    background: '#999999'
  },
  views: [
    {
      type: 'image',
      src: '',
      css: {
        position: 'absolute',
        left: '0rpx',
        top: '0rpx',
        width: '600rpx',
        height: '920rpx'
      }
    },
    {
      type: 'text',
      text: '',
      css: {
        position: 'absolute',
        color: '#ffffff',
        left: '40rpx',
        top: '850rpx',
        fontSize: '28rpx',
        fontWeight: 'bold'
      }
    },
    {
      type: 'text',
      text: '',
      css: {
        position: 'absolute',
        color: '#ffffff',
        left: '40rpx',
        top: '890rpx',
        fontSize: '20rpx'
      }
    },
    {
      type: 'text',
      text: '',
      css: {
        position: 'absolute',
        color: '#333333',
        left: '200rpx',
        top: '650rpx',
        fontSize: '24rpx',
        fontWeight: 'bold',
        zIndex: 999
      }
    }
  ]
});
onMounted(async () => {
  inviteCode.value = userStore.userInfo.uid;
  inviteLink.value = userStore.inviteLink + userStore.userInfo.uid;
  posterConfig.views[1].text = `${useT('扫码注册')} x-verse`;
  posterConfig.views[2].text = `${useT('下载APP')}`;
  posterConfig.views[3].text = `${useT('邀请码')}:${inviteCode.value}`;

  setTimeout(() => {
    qrcode.value._makeCode();
  }, 1000);
  // 获取推广海报
  try {
    const response = await getSpreadBanner({ type: '0' });
    if (response.status === 200 && response.data && response.data.length > 0) {
      // 将接口返回的图片替换到海报配置中
      posterConfig.views[0].src = response.data[0].pic;
    }
  } catch (error) {
    console.error('获取推广海报失败：', error);
  }
});
// 方法定义
// 二维码生成结果
const qrcode = ref(null);
const qrcodeSrc = ref('');

const onQrcodeResult = (result) => {
  console.log('====>QRresult', result);
  qrcodeSrc.value = result;
  posterConfig.views.push({
    type: 'image',
    src: result,
    css: {
      position: 'absolute',
      left: '150rpx',
      top: '300rpx',
      width: '300rpx',
      height: '300rpx'
    }
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示邀请规则
const showRules = () => {
  uni.showModal({
    title: useT('邀请规则'),
    content: useT('1. 邀请好友注册可获得佣金奖励\n2. 佣金比例根据邀请人数递增\n3. 具体规则请查看详细说明'),
    showCancel: false,
    confirmText: useT('我知道了')
  });
};

// 复制邀请码
const copyInviteCode = () => {
  uni.setClipboardData({
    data: inviteCode.value,
    success: () => {
      uni.showToast({
        title: useT('邀请码已复制'),
        icon: 'success'
      });
    }
  });
};

// 复制邀请链接
const copyInviteLink = () => {
  uni.setClipboardData({
    data: inviteLink.value,
    success: () => {
      uni.showToast({
        title: useT('邀请链接已复制'),
        icon: 'success'
      });
    }
  });
};

// 查看邀请海报
const viewPoster = async () => {
  const result = await poster.value.exportImage();
  console.log('====>result', result);
  posterImage.value = result;
  showPoster.value = true;
};

// 关闭海报弹窗
const closePoster = () => {
  showPoster.value = false;
};

// 海报生成成功
const onPosterSuccess = (result) => {
  console.log('海报生成成功', result);
  uni.showToast({
    title: useT('海报生成成功'),
    icon: 'success'
  });
};

// 下载海报
const downloadPoster = async () => {
  try {
    uni.showLoading({ title: useT('海报生成中') });
    const result = await poster.value.exportImage();
    console.log('====>result', result);
    // #ifdef APP-PLUS

    uni.saveImageToPhotosAlbum({
      filePath: result.path,
      success: () => {
        uni.hideLoading();
        uni.showToast({
          title: useT('海报已保存到相册'),
          icon: 'success'
        });
      },
      complete: (complete) => {
        console.log('====>complete', complete);
        uni.hideLoading();
      }
    });
    // #endif
    // #ifdef H5
    //result.path 是base64图片，需要下载
    const a = document.createElement('a');
    a.href = result.path;
    a.download = '海报.png';
    a.click();
    uni.hideLoading();
    // #endif
  } catch (error) {
    uni.hideLoading();
    console.log('海报生成失败', error);
    uni.showToast({
      title: useT('海报生成失败'),
      icon: 'none'
    });
  }
};
</script>

<style lang="scss" scoped>
.invite-page {
  min-height: 100vh;
  background: #fff;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 15px;
  margin-top: var(--status-bar-height);
}

.navbar-left {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.navbar-right {
  width: 40px;
}

.page-content {
  padding-top: calc(var(--status-bar-height) + 45px);
  padding-bottom: 20px;
}

.invite-details {
  text-align: left;
  padding: 30px 20px;

  .commission-text {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;

    .highlight {
      color: #12c284;
    }
  }

  .sub-text {
    font-size: 14px;
    color: #666;
    margin-bottom: 20px;
  }

  .rules-link {
    font-size: 14px;
    color: #12c284;
    text-decoration: underline;
    display: inline-block;
  }
}

.illustration-section {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.invite-bg-image {
  width: 300px;
  height: 200px;
  border-radius: 10px;
}

.invite-info-card {
  margin: 20px;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.info-item {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.info-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-value {
  font-size: 14px;
  color: #333;
  flex: 1;
  word-break: break-all;
}

.copy-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f9f4;
  border-radius: 6px;
  margin-left: 10px;
}

.action-button {
  margin: 20px;
  height: 50px;
  background: #12c284;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(18, 194, 132, 0.3);
}
.qrcode-container {
  height: 0rpx;
  overflow: hidden;
}

// 海报弹窗样式
.poster-container {
  border-radius: 10px;
  .poster-image {
    margin: 0 40rpx;
    margin-bottom: 120rpx;
    .poster-image-item {
      width: 100%;
      display: block;
    }
  }
}

.poster-actions {
  background-color: #fff;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 20rpx;
}

.download-btn {
  width: 200px;
  height: 40px;
  background: #12c284;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;
}

.cancel-btn {
  font-size: 14px;
  color: #666;
  text-decoration: underline;
}
</style>
